package com.reebake.ideal.security.handler;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.reebake.ideal.cache.helper.TimesCacheHelper;
import com.reebake.ideal.captcha.core.SmartCaptchaService;
import com.reebake.ideal.captcha.entity.CaptchaRequestEntity;
import com.reebake.ideal.captcha.entity.CaptchaResponseEntity;
import com.reebake.ideal.security.properties.ServerSecurityProperties;
import com.reebake.ideal.servlet.util.WebUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;

public class AuthenticationCaptchaHandler {
    private final TimesCacheHelper loginFailureTimesCacheHelper = new TimesCacheHelper(LoginAuthenticationEventHandler.LOGIN_FAILURE_TIMES);
    @Autowired
    private ServerSecurityProperties serverSecurityProperties;
    @Autowired
    private SmartCaptchaService smartCaptchaService;

    public Boolean requireCaptcha(String username) {
        Integer maxCaptchaTriggerTimes = serverSecurityProperties.getMaxCaptchaTriggerTimes();
        return maxCaptchaTriggerTimes > 0 && loginFailureTimesCacheHelper.getTimes(username) > maxCaptchaTriggerTimes;
    }

    @SneakyThrows
    public void checkCaptcha(String username, Object captcha) {
        CaptchaRequestEntity captchaVerification = (CaptchaRequestEntity) captcha;
        if (StrUtil.isBlank(username)) {
            throw new BadCredentialsException("username not found");
        }
        if(!requireCaptcha(username)) {
            return;
        }
        if (ObjUtil.isNull(captchaVerification)) {
            throw new BadCredentialsException("captcha not found");
        }
        CaptchaResponseEntity result = smartCaptchaService.verify(captchaVerification);
        if(!result.isSuccess()) {
            throw new BadCredentialsException("captcha verify failure");
        }
    }
}
